package com.ttmusic.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ttmusic.activitys.MainActivity;
import com.ttmusic.activitys.R;


/**
 * 
 * @author wuchangyong
 *
 */
public class Utils {
	
	/**
	 * 友好的提示语
	 */
	public static String[] friendly = {
		"每一天都是崭新的", 
		"此刻有音乐，我不孤独",
		"一首歌，一杯茶，品味人生",
		"No Zuo No Die.",
		"You are My Super Star.",
		"You will Never Walk alone.",
		"身无彩凤双飞翼，但是心有灵犀",
		"君问归期未有期，但是心有灵犀",
		"刚好遇见你在最美的时光",
		"先定个小目标，2018年先挣它1个亿",
		"人丑嘴不甜，长得磕碜还没钱",
		"我走过最长最远的路，就是你的套路",
		"如果帅也是一种罪，那我已罪无可赦",
		"有一种不成文的病历表，叫相思病",
		"姐不是巴黎欧莱雅，你不值得拥有",
		"青春留不住，莫让光阴虚空度",
		"万丈高楼平地起，辉煌还要靠自己",
		"减肥大业，总是在吃饱喝足之后才想起",
		"我做菜的水平特别的菜",
		"天若有情天亦老， 羊肠大道随你跑",
		"爱国爱家爱师妹，防贼防盗防师兄",
		"人之所以能，是相信能",
		"有钱的劳斯莱斯，没钱的劳死累死"
	};
	
	
	
    public static int getStatusBarHeight(Resources res) {
        int result = 0;
        int resourceId = res.getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = res.getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 获取没动画的intent
     *
     * @return
     */
    public static Intent getActIntent(Context context, Class<?> actClass) {
        Intent intent = new Intent(context, actClass);
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        return intent;
    }

    /**
     * 隐藏软键盘
     *
     * @param act
     */
    public static void hideSoftInput(Activity act) {
        try {
            if (act == null) {
                return;
            }
            final View v = act.getWindow().peekDecorView();
            if (v != null && v.getWindowToken() != null) {
                InputMethodManager imm = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示软键盘
     *
     * @param context
     */
    public static void showSoftInput(Activity act) {
        try {
            InputMethodManager m = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
            m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 列表的数据 的第一个 可以被取出 并且 不是null
     *
     * @param list
     * @return
     */
    public static boolean canFetchFirst(List<?> list) {
        return list != null && list.size() > 0 && list.get(0) != null;
    }

    public static void safeClose(Cursor cursor) {
        try {
            cursor.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    
    /**
     * 获取高度
     * @param context
     * @return
     */
    public static int getHeight(Context context){
        WindowManager manager=(WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm=new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }
    /**
     * 获取宽度
     * @param context
     * @return
     */
    public static int getWidth(Context context){
        WindowManager manager=(WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm=new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }
    
    /**
     * 获取Activity高度
     * @param activity
     * @return
     */
    public static int getActivityHeight(Activity activity){
        return  activity.getWindow().getDecorView().getHeight();
    }
    
    private static Fragment current;
    /**
     * fragment切换的方法
     * @param fragmentManager
     * @param from 要切换的原fragment 初次进入时传入null
     * @param to 要切换的新fragment 不能为null
     * @param id 要展示在哪里？
     */
	public static void go(FragmentManager fragmentManager, Fragment from, Fragment to, int id){
		if(current != to) {
			current = to;
			
			FragmentTransaction transaction = fragmentManager.beginTransaction();
			//如果from 不为null 就隐藏
			if(null != from) {
				MainActivity.previous = from;
				transaction.hide(from);
			}
			if(to.isAdded()) {
				//如果添加过就直接show
				transaction.show(to);
			} else {
				//如果没添加过就添加
				transaction.add(R.id.framecontent, to).show(to);
			}
			MainActivity.current = to;
			transaction.commit();
		}
	}
	
	/**
	 * 判断android手机是否已挂载外置SD卡
	 * @param context
	 * @return
	 */
	private static boolean isSDMounted(Context context) {  
	    boolean isMounted = false;  
	    StorageManager sm = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);  
	  
	    try {  
	        Method getVolumList = StorageManager.class.getMethod("getVolumeList", null);  
	        getVolumList.setAccessible(true);  
	        Object[] results = (Object[])getVolumList.invoke(sm, null);  
	        if (results != null) {  
	            for (Object result : results) {  
	                Method mRemoveable = result.getClass().getMethod("isRemovable", null);  
	                Boolean isRemovable = (Boolean) mRemoveable.invoke(result, null);  
	                if (isRemovable) {  
	                    Method getPath = result.getClass().getMethod("getPath", null);  
	                    String path = (String) mRemoveable.invoke(result, null);  
	                    Method getState = sm.getClass().getMethod("getVolumeState", String.class);  
	                    String state = (String)getState.invoke(sm, path);  
	                    if (state.equals(Environment.MEDIA_MOUNTED)) {  
	                        isMounted = true;  
	                        break;  
	                    }  
	                }  
	            }  
	        }  
	    } catch (NoSuchMethodException e){  
	          e.printStackTrace();  
	    } catch (IllegalAccessException e){  
	          e.printStackTrace();  
	    } catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} 
	    return isMounted;  
	}  
	
	/**
     * 遍历 "system/etc/vold.fstab” 文件，获取全部的Android的挂载点信息
     * 
     * @return
     */
    private static ArrayList<String> getDevMountList() {
    	BufferedReader br = null;
    	ArrayList<String> out = new ArrayList<String>();
    	try {
    		br = new BufferedReader(new InputStreamReader(new FileInputStream("/etc/vold.fstab"), "utf-8"));
	    	String voldStr = "" , str = "";
	    	
	    	while((str = br.readLine()) != null) {
	    		voldStr += str + " ";
	    	}
	    	
	        String[] toSearch = voldStr.split(" ");
	        for (int i = 0; i < toSearch.length; i++) {
	            if (toSearch[i].contains("dev_mount")) {
	                if (new File(toSearch[i + 2]).exists()) {
	                    out.add(toSearch[i + 2]);
	                }
	            }
	        }
    	}catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(null != br) br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
    	return out;
    }
	
    /**
     * 获取扩展SD卡存储目录
     * 
     * 如果有外接的SD卡，并且已挂载，则返回这个外置SD卡目录
     * 否则：返回内置SD卡目录
     * @param context
     * @return
     */
    @SuppressLint("SimpleDateFormat")
	public static String getExternalSdCardPath(Context context) {

    	//如果已挂载外置SD卡 则直接返回
        if (isSDMounted(context)) {
            File sdCardFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
            return sdCardFile.getAbsolutePath();
        }

        //否则获取内置的可写的SD卡  因为要往里面存文件
        String path = null;

        File sdCardFile = null;

        ArrayList<String> devMountList = getDevMountList();

        for (String devMount : devMountList) {
            File file = new File(devMount);

            if (file.isDirectory() && file.canWrite()) {
                path = file.getAbsolutePath();

                String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
                File testWritable = new File(path, "test_" + timeStamp);

                if (testWritable.mkdirs()) {
                    testWritable.delete();
                } else {
                    path = null;
                }
            }
        }
        if (path != null) {
            sdCardFile = new File(path);
            return sdCardFile.getAbsolutePath();
        }
        return null;
    }
    
    /**
     * 设置MenuItem的icon图标可见
     * 	利用反射机制调用MenuBuilder的setOptionalIconsVisible方法设置mOptionalIconsVisible为true
     * @param menu
     * @param enable
     */
    public static void setIconEnable(Menu menu, boolean enable) {  
        try {  
            Class<?> clazz = Class.forName("com.android.internal.view.menu.MenuBuilder");  
            Method m = clazz.getDeclaredMethod("setOptionalIconsVisible", boolean.class);  
            m.setAccessible(true);  
            //MenuBuilder实现Menu接口，创建菜单时，传进来的menu其实就是MenuBuilder对象(java的多态特征)  
            m.invoke(menu, enable);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    } 
    
	
}
